<template>
  <div id="baseinfoVehicle" class="list">
    <div class="breadcrumb">
			<Breadcrumb separator=">">
				<BreadcrumbItem to="">基础信息管理</BreadcrumbItem>
				<BreadcrumbItem to="/baseinfo/vehicle">车辆管理</BreadcrumbItem>
			</Breadcrumb>
			<div class="btns">
				<ButtonGroup>
	        <Button type="text" @click="showAdd"><i class="fa fa-plus"></i><span>添加</span></Button>
	        <!--<Button type="text" @click="downloadModel"><i class="fa fa-file"></i><span>下载模板</span></Button>
	        <Button type="text" @click="showImport"><i class="fa fa-upload"></i><span>批量导入</span></Button>-->
	        <Button type="text" @click="exportVehicle"><i class="fa fa-download"></i><span>导出数据</span></Button>
	    	</ButtonGroup>
			</div>
		</div>
    <TableSearch>
      <Form :model="searchForm" :label-width="80">
        <Row :gutter="16">
          <Col :md="8">
            <FormItem label="机构">
              <Select placeholder="请选择" clearable  v-model="searchForm.orgIds" :multiple="true">
                <OrgTreeOption></OrgTreeOption>
              </Select>
		        </FormItem>
          </Col>
          <Col :md="8">
            <FormItem label="车牌号">
              <VehicleComplete v-model="searchForm.vehicleIds" :multiple="false"></VehicleComplete>
            </FormItem>
          </Col>
        </Row>
      </Form>
			<Button type="primary" class="search-btn" icon="search" @click="search()" long>查询</Button>
		</TableSearch>

    <div class="table-content">
			<div class="table">
				<table>
					<thead>
						<th>车牌号</th>
						<th>车主</th>
						<th>车辆识别码</th>
						<th>发动机号</th>
						<th>注册日期</th>
						<th>所属机构</th>
						<th>操作</th>
					</thead>
					<tbody>
            <tr v-for="(v,i) in pageData.thisPageElements" :key="`vehicle-list-key-${i}`">
							<td>{{v.plateNumber}}</td>
							<td>{{v.owner}}</td>
							<td>{{v.vin==null?'--':v.vin}}</td>
							<td>{{v.engineNumber}}</td>
							<td>{{v.regDate==null?'--':moment(v.regDate).format('YYYY-MM-DD')}}</td>
							<td>{{v.orgName}}</td>
							<td class="operate">
                <a @click="openView(v.id)">查看</a>
								<a @click="openEdit(v.id)">编辑</a>
								<a @click="showAlloc(v.id)">调动</a>
								<a @click="doDelete(v)">删除</a>
							</td>
						</tr>
             <tr v-if="!isLoading && pageData.totalNumberOfElements <= 0">
              <td colspan="7">暂无数据</td>
            </tr>
					</tbody>
				</table>
			</div>

      <Page :total="pageData.totalNumberOfElements" :page-size="pageData.pageSize" :current="current" @on-change="loadPage" show-total></Page>
			<Spin size="large" fix v-if="isLoading"></Spin>
		</div>

    <VehicleModal v-model="modal.value" :model="modal.model" :data-id="modal.dataid"  @edit="onEdit" @add="onAdd"></VehicleModal>

    <ImportModal v-model="importModal.show" :submit-path="importModal.path"></ImportModal>

    <!-- 车辆调动  -->
    <Modal v-model="vehicleAllocModal"  title="调动" width="500">
      <Form :label-width="120" :model="allocForm"  ref="allocForm"  :rules="allocRules" >
         <FormItem label="车牌号" >
           {{viewData.plateNumber}}
         </FormItem>
         <FormItem label="当前所在机构" >
           {{viewData.orgName}}
         </FormItem>
         <FormItem label="选择要调入的机构" prop="targetOrgId">
           <Select v-model="allocForm.targetOrgId" placeholder="选择机构"  :transfer="true">
             <OrgTreeOption></OrgTreeOption>
           </Select>
         </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="vehicleAllocModal = false">取消</Button>
        <Button type="primary" :loading="isModalLoading" @click="allocSubmit">保存</Button>
      </div>
    </Modal>


  </div>
</template>

<script>
  import VehicleModal from './VehicleModal'
  import {mapState,mapActions} from 'vuex'
  import moment                from 'moment'
  import {download,post}  					 from '@/util/request'
  export default {
    components:{
      VehicleModal
    },
    mounted(){

    },
    data(){
      return {
        current:1,
        searchForm:{orgIds:[],vehicleIds:''},
        allocForm:{targetOrgId:'',id:'',plateNumber:''},
		allocRules:{
          targetOrgId:{required:true,message:'请选择调入的机构',trigger:'change'}
        },
        modal:{
          value:false,
          model:0, // 0：新增，1：查看，2：编辑
          dataid:null
        },
        vehicleAllocModal:false,
        importModal:{
          show:false,
          path:'sdfasdfadsfa'
        }
      };
    },
    computed:{
      ...mapState('base',['userinfo']),
      ...mapState('baseinfo/baseinfoVehicle',['pageData','isLoading','isModalLoading','viewData'])
    },
    methods:{
      moment,
      ...mapActions('baseinfo/baseinfoVehicle',['reload','delete','loadView']),
      showAlloc(id){
        this.vehicleAllocModal = true;
        this.loadView(id);
      },
      async allocSubmit(){
		let v = await this.$refs.allocForm.validate();
		if(v){
			this.isModalLoading = true;
			this.allocForm.plateNumber=this.viewData.plateNumber;
			this.allocForm.id=this.viewData.id;
			let res = await post("/base/vehicle/vehicleTransfer",this.allocForm);
			this.isModalLoading = false;
			if (res.data.success){
			  this.$Message.success('保存成功');
			  this.allocForm={targetOrgId:'',id:'',plateNumber:''};
			  this.loadPage(this.current);
			  this.vehicleAllocModal=false;
			}else{
			  this.$Message.error(res.data.msg);
			}
		}

      },
      search(){
        this.searchForm = {
          orgIds:this.searchForm.orgIds.join(','),
          vehicleIds:this.searchForm.vehicleIds
        }
        this.loadPage(1);
      },
      loadPage(n){
        this.current = n;
        this.reload({
          pageNum:this.current,
          ...this.searchForm
        });
      },
      openView(id){
        this.modal.model = 1;
        this.modal.value = true;
        this.loadView(id);
      },
      openEdit(id){
        this.modal.model = 2;
        this.modal.value = true;
        this.loadView(id);
      },
      close(){
        this.modal.value = false;
      },
      showAdd(){
        this.modal.dataid = null;
        this.modal.model = 0;
        this.modal.value = true;
      },
      showImport(){
        this.importModal.show = true;
      },
      onAdd(){
        this.loadPage(1);
      },
      onEdit(){
        this.loadPage(this.current);
      },
      deleteLoadPage(){
          let total = this.pageData.totalNumberOfElements - 1;
          let pageSize = parseInt(total / this.pageData.pageSize) + (total % this.pageData.pageSize > 0 ? 1 : 0);
          if (this.current > 1 && this.current > pageSize) {
            this.current--;
          }
          this.loadPage(this.current);
        },
      async doDelete(v){
        this.$Modal.confirm({
          title: '删除车辆',
          content: `是否将车辆“${v.plateNumber}”删除？`,
          loading: true,
          onOk:async ()=>{
            let res = await this.delete({id:v.id});
            if(res.success){
              this.$Modal.remove();
              this.deleteLoadPage();
              this.$Message.success('删除成功');
            }else{
              this.$Modal.remove();
              this.$Message.error(res.msg);
            }
          }
        });
			},
      exportVehicle(){
        download('/base/vehicle/export',this.searchForm);
      },
      downloadModel(){
        	window.location.href="/static/template/vehicle_model.xlsx";
      },

    }
  }
</script>
